<template><!-- eslint-disable-next-line -->
  <div class="submit-index">


    <ul>
    <!-- 表格 -->
    <li style="width: 100%">
      <!-- 只看我的 -->
    <div>
      <el-checkbox style="float: right;margin-bottom: 10px;margin-right: 5px;" v-model="checked" @change="onlyMe">只看我的</el-checkbox>

    </div>
    <!-- 内容     -->
    <el-table :data="tableData"   style="font-size: 80%;line-height: 75%;"
      @sort-change="sortChange">


      <el-table-column prop="id" label="运行ID" width="100" align="center">
        <template slot-scope="scope">
          <a href="javascript:void(0)" @click="showSubmitDetail(scope.row)">
            <div v-html=" formatterId(scope.row)"></div>
            <!-- {{ getUserName(scope.row.userId) }} -->
          </a>
        </template>
      </el-table-column>
      <!-- 用户名 -->
      <el-table-column label="用户名" width="120" align="center">
        <template slot-scope="scope">
          <router-link target="_blank" :to="'/main/user/detail/'+scope.row.userId">
            <div v-html=" getUserName(scope.row.userId)"></div>
            <!-- {{ getUserName(scope.row.userId) }} -->
          </router-link>
        </template>
      </el-table-column>

      <!-- 题目信息 -->
      <el-table-column label="题号"  >
        <template slot="header" slot-scope="scope">
          <!-- eslint-disable-next-line -->
          <!-- <el-link :des="scope.id" @click="" >运行结果 <i class="el-icon-caret-bottom"></i></el-link> -->
          <!-- <el-select v-model="form.region" placeholder="请选择活动区域" style="border: 0px;height: 20px;width: 100px;" :des="scope.id">
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select> -->
            <select :de="scope.id"  v-model="params.problemId" style="border: 0px;height: 20px;font-weight: 550;color: #909399;" placeholder="题号" @change="getTableData(params)">
                <option value="" style="margin: 10px;">题号</option>
                <option style="text-align: center;" v-for=" item in contestProblemList" :key="item.id" :value="item.problemId" >{{ $MyUtils.numToString(item.sequence-1) }}</option>

            </select>
        </template>

        <template slot-scope="scope">
          <router-link target="_blank" :to="'/main/contest/problem/'+problemContestIdByProblemId(scope.row.problemId)+'/'+scope.row.contestId">
            <!-- {{ (parseInt("A", 16)+item.sequence-1).toString(16).toUpperCase()+': ' }} -->
            <div v-html="getProblemTitle(scope.row)"></div>
            <!-- {{  }} -->
          </router-link>
        </template>
      </el-table-column>

      <!-- 运行结果 -->
      <el-table-column align="center" width="100" >
        <template slot="header" slot-scope="scope">
          <!-- eslint-disable-next-line -->
          <!-- <el-link :des="scope.id" @click="" >运行结果 <i class="el-icon-caret-bottom"></i></el-link> -->
          <!-- <el-select v-model="form.region" placeholder="请选择活动区域" style="border: 0px;height: 20px;width: 100px;" :des="scope.id">
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select> -->
            <select :des="scope.id"  v-model="params.errorStatus" style="border: 0px;height: 20px;font-weight: 550;color: #909399;" placeholder="运行结果" @change="getTableData(params)">
                <option value="" style="margin: 10px;">运行结果</option>
                <option :value="0" >{{ModeData.submit.status[0]}}</option>
                <option :value="1">{{ModeData.submit.status[1]}}</option>
                <option :value="2">{{ModeData.submit.status[2]}}</option>
                <option :value="3">{{ModeData.submit.status[3]}}</option>
                <option :value="4">{{ModeData.submit.status[4]}}</option>
                <option :value="5">{{ModeData.submit.status[5]}}</option>
                <option :value="6">{{ModeData.submit.status[6]}}</option>
                <option :value="7">{{ModeData.submit.status[7]}}</option>
            </select>
        </template>
        <template slot-scope="scope" >
          <a href="javascript:void(0)"  @click="showSubmitDetail(scope.row)">
            <div v-html=" getProblemResult(scope.row.errorStatus)"></div>
          </a>
        </template>
      </el-table-column>
      <el-table-column
        prop="time"
        label="运行时间(ms)" width="130" sortable="custom" align="center">
      </el-table-column>
      <el-table-column
        prop="memory"
        label="使用内存(KB)" width="130" sortable="custom" align="center">
      </el-table-column>
      <!-- 代码长度 -->
      <el-table-column label="代码长度" sortable="custom" prop="length" width="100" align="center">
        <template slot-scope="scope">
          {{ scope.row.length }}
        </template>
      </el-table-column>

      <el-table-column align="center" width="100" >
        <template slot="header" slot-scope="scope">
          <!-- eslint-disable-next-line -->
          <!-- <el-link :des="scope.id" @click="" >运行结果 <i class="el-icon-caret-bottom"></i></el-link> -->
          <!-- <el-select v-model="form.region" placeholder="请选择活动区域" style="border: 0px;height: 20px;width: 100px;" :des="scope.id">
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select> -->
            <select :des="scope.id" v-model="params.language" style="border: 0px;height: 20px;font-weight: 550;color: #909399;" placeholder="使用语言" @change="getTableData(params)">
                <option value="" style="margin: 10px;">使用语言</option>
                <option value="java" >Java</option>
                <option value="c++">C/C++</option>
                <option value="python">Python</option>


            </select>
        </template>
        <template slot-scope="scope" >

          {{ scope.row.language }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="提交时间"  width="180" align="center">
      </el-table-column>
      <el-table-column  label="操作" width="120" align="center" v-if="isAdmin()">
        <template slot-scope="scope">
          <el-button :loading="reloads[scope.$index] " @click.native.prevent="reSubmit(scope.row,scope.$index)"
            type="text" size="small">
            重新评测
          </el-button>
        </template>
      </el-table-column>
    </el-table>
            <!--分页-->
    <div class="page">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="params.size"
        :page-sizes="[10,20,30,50,100]"
        @current-change="chg"
        @size-change="chgsize"
        >
      </el-pagination>
    </div>
    </li >

  </ul>

    <!-- 提交详情弹出框 -->
    <el-dialog
      title="代码查看"
      :visible.sync="dialogVisible"
      width="95%"
      style="text-align: left;">
        <div style="font-weight: 700;"><router-link target="_blank" :to="'/main/user/detail/'+submitDetail.userId">
              <span style="color: #c177e7;" v-html=" getUserName(submitDetail.userId)"></span>
              <!-- {{ getUserName(scope.row.userId) }} -->
            </router-link> 提交的代码
        </div>
        <ul class="submit-detail">
          <li style="width:220px">提交时间：{{submitDetail.createTime}}   </li>
          <li style="width:100px"> 语言：{{ submitDetail.language }} </li>
          <li style="width:140px">代码长度：{{ submitDetail.length }}  </li>
          <li style="width:140px">运行时间： {{ submitDetail.time }} ms </li>
          <li style="width:140px">占用内存：{{submitDetail.memory}}K </li>
        </ul>
        <div><div v-html="'运行状态：' + getProblemResult(submitDetail.errorStatus)"></div></div>
        <mavonEditor v-if="submitDetail.errorMsg"  :ishljs = "true" :editable="false" :toolbarsFlag = "false" :defaultOpen="'preview'" :subfield="false" v-model="submitDetail.errorMsg" style="min-height: 20px"/>

        <!-- 代码 -->
        <mavonEditor  :ishljs = "true" :editable="false" :toolbarsFlag = "false" :defaultOpen="'preview'" :subfield="false" v-model="submitDetail.code" style="min-height: 20px"/>

        <hr/>
        <h3>测试点详情</h3>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import * as submitApi from '@/api/submit'
import * as problemApi from '@/api/problem'
import {getEasyUserById} from '@/api/admin'
import ModeData from '@/assets/data';
import {loginUser,isAdmin} from '@/utils/auth'
import {MySleep} from '@/utils/MyUtil'
import { mavonEditor } from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
export default {
  name: 'submitList',

  data() {
    return {
      tableData:[],  //数据
      total:0, //总数据条数
      params:{
        key:"",
        page:1,
        size:10,
        field:null,
        order:null,
        errorStatus:"",
        problemId:"",
        language:"",
      },    //请求参数
      problemNames:{},
      userNames:{},
      ModeData:ModeData,
      reloads:[],  //重新评测
      checked:false,
      dialogVisible:false,
      submitDetail:{},

    };
  },
  props:["contestProblemList","showDetail"],
  components: {
    mavonEditor,   //markdown编译器
  },
  methods: {
    isAdmin(){
      return isAdmin();
    },
    showSubmitDetail(data){
      // console.info(data);
      // if(!this.showDetail && data.userId != loginUser().id)return ;
      this.dialogVisible = true;
      this.submitDetail = JSON.parse(JSON.stringify(data));
      this.submitDetail.code = '```'+data.language+'\n'+data.code+"\n```";
      if(this.submitDetail.errorMsg)this.submitDetail.errorMsg = '```'+data.errorMsg+'```';
    },
    //只看我的
    onlyMe(){
      if(this.checked){
        //展示左侧信息

        this.params.userId= loginUser().id;
      }else this.params.userId = null;


      this.getTableData(this.params);
    },

    reSubmit(row,index){
      // console.info(scope)
      // this.reloads[index] = true;

      // console.info( this.reloads);
      this.$set(this.reloads,index,true)
      // console.info(this.tableData);
      // this.tableData[index].reload = true;
      // console.info((this.$refs['reload_'+index]).setAttribute("loading",true));
      submitApi.submitReload({"id":row.id}).then(res=>{
        if(res.data.success){
          MySleep(3000)
          this.getTableData(this.params);
          this.reloads = [];
        }
      })
    },
    async getTableData(params){
      // var param = this.params;
      // console.info(param);
      var param = JSON.parse(JSON.stringify(params));
      // 已设置params.contestId
      // if(param.problemId==""){ //全选比赛所有题目，
      //   param.problemId = [];
      //   for(var j = 0;j< this.contestProblemList.length;j++){
      //     param.problemId.push(this.contestProblemList[j].problemId);
      //   }
      // }
      await submitApi.getSubmitListApi(param).then(async res=>{
        if(res.data.data){
          var tables = res.data.data.dataList;
          this.total = res.data.data.total;
          //获取名字
          for(var i = 0;i<tables.length;i++){

            if(!this.problemNames[tables[i].problemId]){
              for(var k = 0;k<this.contestProblemList.length;k++){
                if(this.contestProblemList[k].problemId==tables[i].problemId){
                  //题目标题+题号
                  this.problemNames[tables[i].problemId] = this.contestProblemList[k].contestTitle+"("+(parseInt("A", 16)+this.contestProblemList[k].sequence-1).toString(16).toUpperCase()+")";
                }
              }
            }
          }
          //获取用户名字
          for( i = 0;i<tables.length;i++){
            // console.info(tables[i].userId)
            if(!this.userNames[tables[i].userId]){
              await getEasyUserById({"id":tables[i].userId}).then(res2=>{
                if(res2.data.data&&res2.data.data.username){
                  // console.info("success="+res2.data.data.id);
                  this.userNames[res2.data.data.id] =   res2.data.data.username;
                }else{
                  this.userNames[tables[i].userId] =  '<span style="color:grey">用户已注销</span>';
                }
              });
            }
          }
          // console.info(this.problemNames)
          // console.info(this.userNames)
          this.tableData = tables;
        }
      })
    },
    //根据信息userId获取用户名
    getUserName(id){
      return this.userNames[id];
    },
    //根据problemId获取比赛名称
    getProblemTitle(data){

      // console.info(result)
      // while(result=="");
      return this.problemNames[data.problemId];
    },
    formatterId(row){
      return new String(row.id).substring(0,8)+"..."
    },
    //获取运行结果
    getProblemResult(errorStatus){
      if(errorStatus==null||errorStatus==undefined){
        '<span style="color:grey">未知</span>';
      }
      var color = 'grey';  //初始颜色
      if(errorStatus==0)color="#25bbb5";  //成功
      else if(errorStatus==1)color="red"; //答案错误
      else if(errorStatus==2||errorStatus==3)color = "gray";  //超时/内存超限
      else if(errorStatus==4)color = "#fec10f";  //编译失败
      else if(errorStatus==5)color = "red";  //运行失败
      else if(errorStatus==7) color = "#c6f5cd"; //正在判题
      var res = '';
      if(errorStatus==7){  //正在加载的图标
        res = '<i class="fa fa-spinner fa-spin"></i>';
      }

      return '<span style="color:'+color+'">'+ModeData.submit.status[errorStatus]+'</span>'+res;
    },
    // 自定义排序
    sortChange(column,prop,order){
      // console.info(column);
      this.params.field = column.prop;
      this.params.order = column.order;
      if(this.params.order){
        if(this.params.order[0]=='a')this.params.order = "asc";
        else this.params.order = "desc";
      }else{  this.params.order = "";this.params.field = ''}
      // console.info(this.params)
      this.getTableData(this.params);
    },
    //每页记录数发生改变时
    chgsize(pgsize) {
      //更改每页记录数
      this.params.size = pgsize;
      //从每一页开始查询
      this.params.page = 1;
      //重新查询
      this.getTableData(this.params);
    },
    //当页数发生变化时执行
    chg(curpage) {
        //更新查询的页数
        this.params.page = curpage;
        //重新查询
        this.getTableData(this.params);
    },
    //根据题目id获取题目关联表id
    problemContestIdByProblemId(problemId){
      for(var i = 0;i<this.contestProblemList.length;i++){
        if(this.contestProblemList[i].problemId==problemId)return this.contestProblemList[i].id;
      }
      return null;
    }

  },
  created(){
    // if(this.$route.query){  //根据请求头获取限制条件
    //   this.params = JSON.parse(JSON.stringify(this.$route.query));
    //   console.info(this.params)

    // }

    Object.assign(this.params,this.$route.query)
    this.params.contestId = this.contestProblemList[0].contestId;
    this.getTableData(this.params);

  }


}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.submit-index .submit-detail{
  /* background-color: #ffffff; */
  list-style: none;
  margin-top: 10px;
  padding: 0px;
  color: #999999;
  display: flex;
}
.submit-index .submit-detail li{
  /* background-color: #ffffff; */
  list-style: none;
  margin: 5px;
  padding: 0px;


}
.submit-index > ul{
  list-style: none;
  display: flex;
}
.submit-index > ul > li{
  list-style: none;
}
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card {
  /* width: 480px; */
  width: 100%;
}
</style>
